package com.teradata.controller;

import com.teradata.entity.User;
import com.teradata.repository.UserRespository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Collection;
import java.util.Map;
import java.util.Optional;

@RestController
public class BasicController {

    @Autowired
    UserRespository userRespository;

    @GetMapping("/hello_world")
    public Mono<String> sayHelloWorld() {
        return Mono.just("Hello World");
    }

    @GetMapping
    @ResponseBody
    public Optional<String> index() {
        return Optional.of("optional hello world");
    }

    @GetMapping("/optional")
    @ResponseBody
    public Optional<String> optional(@RequestParam(required = false) String message) {
        return StringUtils.hasText(message) ? Optional.of(message) : Optional.empty() ;
    }

    /**
     * 这里的意思就是Mono，其实可以用Optional来代替
     * @return
     */
    @GetMapping("/mono")
    @ResponseBody
    public Mono<String> mono() {
        return Mono.just("mono hello world");
    }

    @GetMapping("/mono/param")
    @ResponseBody
    public Mono<String> monoparam(@RequestParam String message) {
        return Mono.just(message);
    }

    @PostMapping("/user/save")
    @ResponseBody
    public Mono<User> saveUser(User  user) {
        if (userRespository.saveUser(user)){
            return Mono.just(user);
        }
        return Mono.empty();
    }

    @GetMapping("/user/list")
    @ResponseBody
    public Collection<User> usersList() {
        return userRespository.findAll();
    }

    @GetMapping("/user/fluxlist")
    @ResponseBody
    public Flux<User> usersFluxList() {
        Collection<User> users = userRespository.findAll();
        return Flux.fromIterable(users);
    }

    @GetMapping("/apiParams")
    @ResponseBody
    public Mono<Map<String, String>> getParams(@RequestParam Map<String, String> reqParam){
        return Mono.just(reqParam);
    }



}
